package com.by.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.by.constants.ThumbConstant;
import com.by.mapper.BlogMapper;
import com.by.model.entity.Blog;
import com.by.model.entity.User;
import com.by.model.vo.BlogVO;
import com.by.service.BlogService;
import com.by.service.ThumbService;
import com.by.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author lzh
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements BlogService {

    @Resource
    private UserService userService;

    @Lazy
    @Resource
    private ThumbService thumbService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public BlogVO getBlogVoById(long id, HttpServletRequest request) {
        Blog blog = this.getById(id);
        User loginUser = userService.getLoginUser(request);
        return getBlogVo(blog, loginUser);
    }

    @Override
    public List<BlogVO> getBlogVoList(List<Blog> blogList, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        // 用于判断当前用户是否点赞过该博客
        Map<Long, Boolean> blogIdHashThumbMap = new HashMap<>(blogList.size() * 2);
        if (ObjectUtil.isNotEmpty(loginUser)) {
            // 批量查询用户点赞过的博客ID
            List<Object> blogIdList = blogList.stream()
                    .map(blog -> blog.getId().toString())
                    .collect(Collectors.toList());
            List<Object> thumbList = redisTemplate.opsForHash()
                    .multiGet(ThumbConstant.USER_THUMB_KEY_PREFIX + loginUser.getId(), blogIdList);
            for (Object object : thumbList) {
                if (object == null) {
                    continue;
                }
                blogIdHashThumbMap.put(Long.valueOf(object.toString()), true);
            }
        }
        // 封装返回
        return blogList.stream()
                .map(blog -> {
                    BlogVO blogVO = BeanUtil.copyProperties(blog, BlogVO.class);
                    blogVO.setHasThumb(blogIdHashThumbMap.get(blog.getId()));
                    return blogVO;
                })
                .toList();
    }

    public BlogVO getBlogVo(Blog blog, User loginUser) {
        BlogVO blogVO = new BlogVO();
        BeanUtil.copyProperties(blog, blogVO);
        if (loginUser == null) {
            return blogVO;
        }
        Boolean hasThumb = thumbService.hasThumb(blog.getId(), loginUser.getId());
        blogVO.setHasThumb(hasThumb);
        return blogVO;
    }
}




